package com.bit.blog.common.interceptor;

import com.bit.blog.common.constant.Constants;
import com.bit.blog.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
//拦截器相关类的设置；进行强制要求用户进行登录；
public class LoginInterceptor implements HandlerInterceptor {
    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken=request.getHeader(Constants.USER_TOKEN_HEADER_KEY);//进行获取通过前端传过来的token值；
        log.info("从header中进行获取token:"+userToken);
        if(userToken==null){
            //进行拦截；
            response.setStatus(401);//401表示用户没有进行登录；
            return false;
        }
        //进行校验token是否合法；
        Claims claims= JwtUtils.parseToken(userToken);
        if(claims==null){
            //进行拦截；
            response.setStatus(401);
            return false;
        }
        return true;

//        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
